#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
@FileName  :SerialPortOperation.py
@desc      :
@Author    :Young
@IDE       :PyCharm
@Time      :2022-10-16 14:40
'''
#串口操作相关类

from PyQt5 import QtWidgets
from PyQt5.QtCore import QTimer
import time
import serial
import serial.tools.list_ports
import sys

#自定义
from DBOperation import *
from QT_plot_chart import Ui_MainWindow




def open_port(port, bps, timeout):  # 打开串口
    ret = False
    #print(6666666)
    try:
        # 打开串口，并得到串口对象
        ser = serial.Serial(port, bps, timeout=timeout)
        # 判断是否打开成功
        if ser.is_open:
            ret = True
            print("打开串口操作成功！")
            print(port + "打开了")
    except Exception as e:
        print("---异常---：", e)
    return ret, ser


class Pyqt_Serial(QtWidgets.QMainWindow,Ui_MainWindow):
    def __init__(self):
        super(Pyqt_Serial, self).__init__() # **
        self.receivePort = None  # 接收串口
        self.receiveCondition = False  # 接收串口状态
        self.setupUi(self)
        self.currentTime = None  # 当前时间
        self.currentTemp = None  # 当前温度
        self.currentUser = None  # 当前用户
        self.currentIllumination = None  #当前光照
        self.startReceiveFlag = False
        self.bind()
        #self.open_receive_port()
        self.timer_init() #定时器初始化
        self.setWindowTitle("城市照明监测系统")

    def show(self, username = None, flag = False):
        super().show()
        self.currentUser = username
        self.startReceiveFlag = flag
        print(self.currentUser)
        self.CurrentUser.append(self.currentUser)

    def timer_init(self):
        #使用QTimer，2秒触发一次，更新数据
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.datashow)
        self.timer.start(2000)


    def bind(self):
        '''
        把按钮的点击事件和具体函数绑定
        :return: None
        '''
        self.btn_start.clicked.connect(self.start_receive_data)
        self.btn_stop.clicked.connect(self.reset)

    def start_receive_data(self):
        '''
        Checkin按钮对应函数，完成打开接收端口，开始接收数据的功能
        :return:
        '''
        self.open_receive_port()
        #self.start_receive()
        self.start_receive_temp_and_illumination_info()

    def reset(self):
        '''
        Reset按钮对应函数，完成接收端口的关闭，及接收串口数据的清除
        :return:
        '''
        self.close_receive_port()
        self.clear_receive()

    def open_receive_port(self):
        '''
        打开接收端口
        :return:
        '''
        port = 'COM3'  # 接收接口的名字
        bps = 9600  # 接受接口的波特率
        timeout = None  # 接收接口的连接时间
        # print(2222222)
        self.receiveCondition, self.receivePort = open_port(port, bps, timeout)

    def close_receive_port(self):
        '''
        关闭数据接收端口
        :return: None
        '''
        try:
            # 判断是否打开成功
            if self.receivePort.is_open:
                self.receivePort.close()  # 关闭数据接收端口
                self.receiveCondition = False  # 更新接收端口状态
        except Exception as e:
            print("---异常---：", e)
    def clear_receive(self):
        '''
        清理接收数据界面， 全部清除
        :return:None
        '''
        self.CurrentTime.clear()
        self.CurrentUser.clear()
        self.CurrentLightInfo.clear()
        self.CurrentTemperatureInfo.clear()

    def datashow(self):
        #print("开始接收温度和光照信息……")
        if self.receiveCondition and self.startReceiveFlag:
            self.receivePort.flushInput()  # 清除缓存数据
            print("温度光照信息连接已经建立！")
            text = self.receivePort.read(5).decode('gbk')

            print(text)
            # 24XLX
            self.currentTemp = text[0:2]  # 温度数据
            x2 = text[3:4]  # 光照数据

            if (x2 == "L"):
                self.currentIllumination = "亮"
            else:
                self.currentIllumination = "暗"
            self.currentTime = time.ctime()
            self.CurrentTime.setText(self.currentTime[4:16])
            print("self.currentTime",self.currentTime)
            self.CurrentTemperatureInfo.setText(self.currentTemp+"℃")
            self.CurrentLightInfo.setText(self.currentIllumination)
            #数据库数据存储
            addLightInfo(self.currentTime[4:16], self.currentIllumination)  # 光照数据存数据库
            addHumitureInfo(self.currentTime[4:16], self.currentTemp)  # 光照数据存数据库
            print("数据展示完成")



import sys
if __name__=='__main__':
    app =  QtWidgets.QApplication(sys.argv)
    loginSuccessful = Pyqt_Serial()
    loginSuccessful.show()
    sys.exit(app.exec_())
